package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {


    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        //获取当前登录用户 为购物车对象赋值
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null) {
            throw new CustomException("当前用户未登录('userID获取失败..')");
        }
        shoppingCart.setUserId(currentId);

        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(shoppingCart.getUserId()!=null,ShoppingCart::getUserId,shoppingCart.getUserId());

        Long dishId = shoppingCart.getDishId();

        if (dishId != null) {

            qw.eq(ShoppingCart::getDishId,dishId);
        } else {
            qw.eq(shoppingCart.getSetmealId() != null,ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }

        //SQL:select * from shopping_cart where user_id = ? and dish_id/setmeal_id = ?
        ShoppingCart cart = this.getOne(qw);
        if (cart != null) {
            //表示当前add商品已存在
            cart.setNumber(cart.getNumber() + 1); //在原有数据基础上+1
            this.updateById(cart);
        } else {
            //当前商品不存在
            shoppingCart.setNumber(1);  //默认值设置为1
            shoppingCart.setCreateTime(LocalDateTime.now());
            this.save(shoppingCart);
            cart = shoppingCart;
        }
        return cart;
    }
}
